const express = require('express');
const { WebSocketServer } = require('ws');
const cors = require('cors')

const app = express();
app.use(cors())

const server = app.listen(3000, () => {
    console.log('server is running at port 3000');
});
// 初始化ws
const connection = {};
const wss = new WebSocketServer({ server });

wss.on('connection', (ws) => {
    // 传递{id:1,fingerprint:"dsd",action:"login"}
    ws.on('message', (message) => {
        const data = JSON.parse(message);
        switch (data.action) {
            case 'login':
                // 新设备登录
                if (connection[data.id]?.fingerprint) {
                    connection[data.id].socket.send(JSON.stringify({
                        action: "logout",
                        message: `您于${new Date().toLocaleString()}在其他设备上登录`
                    }))
                    connection[data.id].socket.close();
                    connection[data.id].socket = ws;
                } else {
                    // 第一次登录
                    connection[data.id] = {
                        socket: ws,
                        fingerprint: data.fingerprint
                    }
                }
                break;
            default:
                break;
        }
    });

});